export const decodeUint8Array = uint8Array => {
  const data16 = buf2hex(uint8Array);
  const requestData = hexToStr(data16);
  return requestData
    .replace(/^data:\s*/gm, '')
    .replace(/^(event:message\s*)/gm, '')
    .trim();
};

export const buf2hex = arrayBuffer => {
  return Array.prototype.map
    .call(new Uint8Array(arrayBuffer), x => ('00' + x.toString(16)).slice(-2))
    .join('');
};

/**
 * 手动实现 UTF-8 解码 (兼容微信小程序真机环境)
 * @param {String} hex 十六进制字符串
 * @return {String} 包含中文的字符串
 */
export const hexToStr = hex => {
  // 1. 预处理十六进制字符串
  let hexString = hex.trim();
  if (hexString.startsWith('0x') || hexString.startsWith('0X')) {
    hexString = hexString.slice(2);
  }
  if (hexString.length % 2 !== 0) return '';

  // 2. 转换十六进制为字节数组
  const bytes = [];
  for (let i = 0; i < hexString.length; i += 2) {
    bytes.push(parseInt(hexString.substr(i, 2), 16));
  }

  // 3. 手动实现 UTF-8 解码
  let result = '';
  let i = 0;

  while (i < bytes.length) {
    const byte = bytes[i];

    // ASCII 字符 (单字节)
    if (byte < 0x80) {
      result += String.fromCharCode(byte);
      i += 1;
    }
    // 双字节字符
    else if (byte >= 0xc0 && byte < 0xe0 && i + 1 < bytes.length) {
      const byte2 = bytes[i + 1];
      result += String.fromCharCode(((byte & 0x1f) << 6) | (byte2 & 0x3f));
      i += 2;
    }
    // 三字节字符 (常用汉字)
    else if (byte >= 0xe0 && byte < 0xf0 && i + 2 < bytes.length) {
      const byte2 = bytes[i + 1];
      const byte3 = bytes[i + 2];
      result += String.fromCharCode(
        ((byte & 0x0f) << 12) | ((byte2 & 0x3f) << 6) | (byte3 & 0x3f)
      );
      i += 3;
    }
    // 四字节字符 (不常用字符)
    else if (byte >= 0xf0 && i + 3 < bytes.length) {
      const byte2 = bytes[i + 1];
      const byte3 = bytes[i + 2];
      const byte4 = bytes[i + 3];
      // 转换为代理对表示
      const codePoint =
        ((byte & 0x07) << 18) |
        ((byte2 & 0x3f) << 12) |
        ((byte3 & 0x3f) << 6) |
        (byte4 & 0x3f);

      result += String.fromCharCode(
        0xd800 | ((codePoint - 0x10000) >> 10),
        0xdc00 | (codePoint & 0x3ff)
      );
      i += 4;
    }
    // 无效序列则跳过
    else {
      i++;
    }
  }

  return result;
};
